package com.ms.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * User: gmc
 * Date: 23/03/13
 */
public class GenericUtil {

    public static Class<?> getGenericFrom(Class clazz, int position) {
        return getGenericFrom(clazz, position, true);
    }

    private static Class<?> getGenericFrom(Class clazz, int position, boolean throwException) {
        if (throwException) {
            return getGenericFromInternal(clazz, position);
        } else {
            try {
                return getGenericFromInternal(clazz, position);
            } catch (Exception e) {
                return null;
            }
        }
    }

    private static Class<?> getGenericFromInternal(Class clazz, int position) {
        Type[] genericTypes = ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments();
        Type viewType = genericTypes[position];
        return viewType instanceof Class<?>
                ? (Class<?>) viewType
                : (Class<?>) ((ParameterizedType) viewType).getRawType();
    }

}
